import config from './config';
import Api from './utils/Api'
App({
  onLaunch: function(e) {
    // this.login();
    
  },
  onShow(e) {
    console.log(e);
  },
  globalData: {
    userInfo: {},
    openId: "",
    access_token: "",
    accessInfo:null,
    loginInfo:null
  },
  post(apiKey, body = {}, header = {}) {
    return this._request("POST", apiKey, body, header);
  },
  get(apiKey, body = {}, header = {}) {
    return this._request("GET", apiKey, body, header);
  },
  _request(_type, apiKey, body = {}, header = {}) {
    wx.showNavigationBarLoading();
    let url = (config.isDebug ? config.DEV_URL : config.PRO_URL) + Api[apiKey];
    let token = this.globalData.access_token;
    body.token = token;
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        data: body,
        method: _type,
        header: {
          token: token,
          version: 1,
          platform: "nimiprogram"
        },
        success: (d) => {
          wx.hideNavigationBarLoading();
          config.isDebug && console.log(d);
          if (d.statusCode === 200) {
            if (d.data.code == 300) {
              this.login();
              reject();
            } else {
              resolve(d.data);
            }
          } else {
            reject();
          }
        },
        fail: (e) => {
          this.toast("网络或服务器错误！");
          reject(e);
        }
      })
    })
  },
  log(log) {
    config.isDebug && console.log(log);
  },
  loginLister() {
    this.emitAppListener("appLoginListner")
  },
  emitAppListener(fnName, params = {}) {
    var pages = getCurrentPages();
    for (var i = 0; i < pages.length; i++) {
      if (typeof pages[i][fnName] == 'function') {
        pages[i][fnName](params);
      }
    }
  },
  gobackByPageName(pageName, params = {}, isUnload = false) {
    if (pageName) {
      var pages = getCurrentPages();
      for (var i = pages.length - 1; i >= 0; i--) {
        var backIndex = pages.length - i - 1;
        if (pages[i].route === pageName || backIndex === pageName) {
          if (typeof pages[i]['gobackByPageNameListener'] == "function") {
            pages[i]['gobackByPageNameListener'](params);
          }
          setTimeout(() => {
            wx.navigateBack({
              delta: isUnload ? backIndex - 1 : backIndex
            })
          })
          return true;
        }
      }
      return false;
    }
  },
  getPage(pageName) {
    var pages = getCurrentPages();
    for (var i = pages.length - 1; i >= 0; i--) {
      if (pages[i].route === pageName) {
        return pages[i];
      }
    }
    return null;
  },
  _getUserInfo(fn) {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo'] == true) {
          wx.getUserInfo({
            success: (res) => {
              this.globalData.userInfo = res;
              fn && fn(true, res);
            }
          })
        } else if (res.authSetting['scope.userInfo'] == false) {
          wx.showModal({
            title: '融酒',
            content: '请授权我们获取您的基本信息。',
            complete: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    this._getUserInfo(fn);
                  },
                  fail: (e) => {
                    fn && fn(false);
                  }
                })
              } else {
                fn && fn(false);
              }
            }
          })
        } else {
          wx.authorize({
            scope: "scope.userInfo",
            success: (res) => {
              this._getUserInfo(fn);
            },
            fail: () => {
              this._getUserInfo(fn);
            }
          })
        }
      }
    })
  },
  toast(msg) {
    wx.showToast({
      title: msg || "",
      icon: "none"
    })
  },
  getUsetInfo(){
    if (this.globalData.accessInfo){
      return this.globalData.accessInfo;
    }else{
      let accsess = wx.getStorageSync("user_info");
      try {
        let info = JSON.parse(accsess);
        //修改token
        this.globalData.access_token = info.token;
        this.globalData.accessInfo = info;
        return info;
      }catch(e){
        return null;
      }
    }
  },
  setUserInfo(infoJson){
    this.globalData.accessInfo = infoJson;
    //修改token
    this.globalData.access_token = infoJson.token;
    wx.setStorage({
      key: 'user_info',
      data: JSON.stringify(infoJson),
    });
  },
  checkLogin(){
    return new Promise((resolve,reject)=>{
      wx.login({
        success: (res) => {
          this.post("codeLogin", { code: res.code })
          .then((res) => {
            if (res.code == 200) {
              resolve(res.data);
              this.setUserInfo(res.data);
            } else {
              reject(res);
            }
          })
          .catch((e) => {
            console.log(e);
            reject(e);
          })
        },
        fail() {
          reject();
        }
      })
    })
  },
  login(){
    wx.navigateTo({
      url: '/pages/accreditLogin/accreditLogin',
    })
  }
});